package cn.diancan.interceptor;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import cn.diancan.model.SysManager;

public class CheckPrivilegeInterceptor extends AbstractInterceptor {

	public String intercept(ActionInvocation invocation) throws Exception {

		// 获取信息
		SysManager manager = (SysManager) ActionContext.getContext().getSession().get("login_manager"); // 当前登录用户
		String namespace = invocation.getProxy().getNamespace();
		String actionName = invocation.getProxy().getActionName();
		String privUrl = namespace+"/" + actionName; // 对应的权限URL
		HttpServletResponse response=ServletActionContext.getResponse();
		HttpServletRequest request= ServletActionContext.getRequest();
		// 如果未登录
		if (manager == null) {
			if (privUrl.startsWith("/manager/Login_toLogin")||privUrl.startsWith("/manager/Login_verifyCode")||privUrl.startsWith("/manager/Login_login")) { // "/user_loginUI", "/user_login"
				// 如果是去登录，就放行
				return invocation.invoke();
			} else {
				// 如果不是去登录，就转到登录页面
				response.sendRedirect(getBasePath(request)+"manager/Login_toLogin");
				return null;
			}
		}else {// 如果已登 录，就判断权限
			if (manager.hasPrivilegeByUrl(privUrl)) {
				// 如果有权限，就放行
				return invocation.invoke();
			} else {
				// 如果没有权限，就转到提示页面
				response.sendRedirect(getBasePath(request)+"/views/ftl/manager/error.ftl");
				return null;
			}
		}
	}
	public String getBasePath(HttpServletRequest request){
		if(80==request.getServerPort()){
			return  request.getScheme()+"://"+request.getServerName()+request.getContextPath()+"/";
		}else{
			return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
		}
	} 

}
